package questions;

/**
 * 哲学家就餐问题
 */
public class Philosopher {
    Chopstick left, right;
    Integer index;

    public Philosopher(Chopstick left, Chopstick right, Integer index) {
        this.left = left;
        this.right = right;
        this.index = index;
    }


    public void eat() {
        //不会死锁
        for (; ; ) {
//            if (index == 0) {//此时相当于单线程执行，一个吃完才能下一个
            if (index % 2 == 0){//偶数拿左手，奇数先右手，多个人可以同时吃
                synchronized (left) {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    synchronized (right) {
                        System.out.println("哲学家" + index + "吃完");
                    }
                }
        } else{
            synchronized (right) {
                synchronized (left) {
                    System.out.println("哲学家" + index + "吃完");
                }
            }
        }
        //死锁
//            synchronized (left) {
//                try {
//                    Thread.sleep(100);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//                synchronized (right) {
//                    try {
//                        Thread.sleep(500);
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
//                    System.out.println("哲学家" + index + "吃完");
//                }
//            }

        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}

    public static void main(String[] args) throws InterruptedException {
        Chopstick c1 = new Chopstick(1);
        Chopstick c2 = new Chopstick(2);
        Chopstick c3 = new Chopstick(3);
        Chopstick c4 = new Chopstick(4);
        Chopstick c5 = new Chopstick(5);

        Philosopher p1 = new Philosopher(c1, c2, 1);
        Philosopher p2 = new Philosopher(c2, c3, 2);
        Philosopher p3 = new Philosopher(c3, c4, 3);
        Philosopher p4 = new Philosopher(c4, c5, 4);
        Philosopher p5 = new Philosopher(c5, c1, 5);
        new Thread(() -> {
            p1.eat();
        }).start();
        new Thread(() -> {
            p2.eat();
        }).start();
        new Thread(() -> {
            p3.eat();
        }).start();
        new Thread(() -> {
            p4.eat();
        }).start();
        new Thread(() -> {
            p5.eat();
        }).start();

        Thread.sleep(10000);

    }
}


class Chopstick {
    Integer index;

    public Chopstick(Integer index) {
        this.index = index;
    }
}